package com.mz.mattress.client.timer;

import com.mz.mattress.api.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@DependsOn("springUtil")
public class TimerService {

    public static final ScheduledExecutorService EXECUTOR = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName("timerThread");
            t.setDaemon(true);
            return t;
        }
    });

    public TimerService() {
        EXECUTOR.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {

                Map<String, TimerTask> map = SpringUtil.getBeansOfType(TimerTask.class);
                for (Map.Entry<String, TimerTask> entry : map.entrySet()) {
                    try {
                        TimerTask task = entry.getValue();
                        if (task.canDo()) {
                            StopWatch stopWatch = new StopWatch();
                            stopWatch.start();
                            log.info("timer_{}_start", entry.getKey());
                            task.run();
                            stopWatch.stop();
                            log.info("timer_{}_end,time={},", entry.getKey(), stopWatch.getTotalTimeMillis());
                        }
                    } catch (Throwable e) {
                        log.error("timer_{}_error", entry.getKey(), e);
                    }
                }

            }
        }, 5, 5, TimeUnit.MINUTES);
    }

}
